# -*- coding: utf-8 -*-

import pygeoip

from django.http import HttpResponse
from django.http import HttpResponseRedirect

from django.template import RequestContext
from django.template.loader import get_template

from django.contrib.auth import get_user
from django.contrib.auth.decorators import login_required

from codename_bamboo.preference import GEOIP_CITY_DATABASE
geoip = pygeoip.GeoIP(GEOIP_CITY_DATABASE)

from forms import *

def index(request):
    """
    Serve people's request for index page request
    """
    if request.user.is_authenticated():
        return HttpResponseRedirect('/home/')
    else:
        signin_form = SignInForm()
        template = get_template('index.dtpl')
        context  = RequestContext(request, {'account': 'signin',
                                            'signin_form': signin_form,
                                            })
        response = HttpResponse(template.render(context))

        if not 'homeLatitude' in request.session or not 'homeLongitude' in request.session:
            record    = geoip.record_by_addr('114.82.3.100') # request.META['REMOTE_ADDR'])
            latitude  = str(record['latitude'])
            longitude = str(record['longitude'])

            request.session['homeLatitude']  = latitude
            request.session['homeLongitude'] = longitude
        else:
            latitude = str(request.session['homeLatitude'])
            longitude = str(request.session['homeLongitude'])

        response.set_cookie('homeLatitude', latitude)
        response.set_cookie('homeLongitude', longitude)

        if 'lastLatitude' in request.session and 'lastLongitude' in request.session:
            latitude  = str(request.session['lastLatitude'])
            longitude = str(request.session['lastLongitude'])

        else:
            latitude = str(request.session['homeLatitude'])
            longitude = str(request.session['homeLongitude'])

        response.set_cookie('lastLatitude', latitude)
        response.set_cookie('lastLongitude', longitude)

        return response
